function avg_tone( idlPath, idlFile, strPath, strFile )
%--------------------------------------------------------------------------
% Average Spectrum of Tone Files
%
% Cooper Baker - 2014
%--------------------------------------------------------------------------

close all;

% Settings
%--------------------------------------------------------------------------
winSize = 512;
overlap = 4;
win     = chebwin( winSize, 125 );
name    = 'Average Spectrum';

% Initializations
%--------------------------------------------------------------------------
if any( exist( 'idlFile' ) ~= 1 )
    [ idlFile, idlPath ] = uigetfile( '*.wav', 'Ideal Audio File' );
    [ strFile, strPath ] = uigetfile( '*.wav', 'Stretched Audio File' );
end

[ idlBuf, sr ] = audioread( [ idlPath, idlFile ] );
[ strBuf, sr ] = audioread( [ strPath, strFile ] );
halfWinSize    = winSize / 2;
idlSize        = length( idlBuf );
strSize        = length( strBuf );
idlMsec        = ( idlSize / sr ) * 1000;
gridMsec       = 500;
gridHops       = gridMsec / ( ( ( winSize / overlap ) / sr ) * 1000 );
hopSize        = winSize / overlap;
hopMsec        = ( hopSize / sr ) * 1000;
idlAvg         = zeros( halfWinSize, 1 );
strAvg         = zeros( halfWinSize, 1 );
index          = 1;
winSum         = sum( win );

% trim or pad stretch buffer to match ideal buffer length
if( idlSize > strSize )
    strBuf = [ strBuf ; zeros( idlSize - strSize, 1 ) ];
elseif( strSize > idlSize )
    strBuf = strBuf( 1 : length( idlBuf ) );
end

% analyze only middle of buffers for 'tone' files padded with silence
hop    = round( idlSize / 3 );
hopMax = round( ( idlSize * 2 ) / 3 );

% Normalization
%--------------------------------------------------------------------------

% get file metadata
idlInfo = audioinfo( [ idlPath, idlFile ] );
strInfo = audioinfo( [ strPath, strFile ] );

% get file normalization coefficient
idlFileNorm = str2num( idlInfo.Title );
strFileNorm = str2num( strInfo.Title );

% de-normalize normalized .wav file data
idlRaw = idlBuf / idlFileNorm;
strRaw = strBuf / strFileNorm;

% make hann window
normWin = hann( round( idlSize / 2 ) );

% copy and window middle of files
idlNormWin = idlRaw( idlSize * 0.25 : idlSize * 0.75 - 1 ) .* normWin;
strNormWin = strRaw( idlSize * 0.25 : idlSize * 0.75 - 1 ) .* normWin;

% calculate rms of windowed file middles
idlRms = rms( idlNormWin );
strRms = rms( strNormWin );

% calculate normalization scalar
strScale = 1 / ( strRms / idlRms );

% scale stretch buffer to match ideal buffer
idlRaw = idlRaw;
strRaw = strRaw * strScale;

% Analysis Loop
%--------------------------------------------------------------------------
while hop < hopMax

    % copy analysis frame from buffer
    idlSamps = idlRaw( hop : hop + winSize - 1 );
    strSamps = strRaw( hop : hop + winSize - 1 );

    % window the frame
    idlWin = idlSamps .* win;
    strWin = strSamps .* win;

    % perform fft
    idlFullSpec = fft( idlWin );
    strFullSpec = fft( strWin );

    % save relevant halves of spectra
    idlSpec = idlFullSpec( 1 : halfWinSize );
    strSpec = strFullSpec( 1 : halfWinSize );

    % calculate magnitude spectra
    idlMag = abs( idlSpec );
    strMag = abs( strSpec );

    % store all magnitude spectra into array
    idlArray( index, : ) = idlMag;
    strArray( index, : ) = strMag;

    % increment indices
    hop = hop + hopSize;
    index = index + 1;
end

% calculate average spectra from all hops
idlMag = sum( idlArray ) / index;
strMag = sum( strArray ) / index;

% calculate amplitude spectra
idlAmp = ( idlMag / winSum );
strAmp = ( strMag / winSum );

% calculate sones spectra
idlSones = idlAmp .^ 0.6;
strSones = strAmp .^ 0.6;

% calculate decibel spectra
idlDb  = 20 * log10( idlAmp );
strDb  = 20 * log10( strAmp );

% copy spectra to plot arrays
idlPlot = idlSones;
strPlot = strSones;

% calculate ideal plot offset
offset = 0;
offset = abs( min( [ min( idlPlot ) min( strPlot ) ] ) );

% offset plots
idlPlot = idlPlot + offset;
strPlot = strPlot + offset;

% calculate absolute difference between plots (error)
difPlot = abs( idlPlot - strPlot );

% calculate mean error value
difMean = sum( difPlot ) / ( halfWinSize );

% calculate max error value
difMax = max( difPlot );

% Plot
%--------------------------------------------------------------------------
fontName   = 'Times New Roman';
fontSize   = 12;
xSpc       = 0.103;
ySpc       = 0.64;

fig = figure( 1 );
set( fig, 'Name', name );
set( fig, 'Position', [ 0 0 800 275 ] );
set( fig, 'defaultAxesFontName', fontName );
set( fig, 'defaultTextFontName', fontName );

% spectra
plot( idlPlot, 'Color', [ 0.2 0.2 0.8 ], 'LineWidth', 6 );
hold on;
plot( strPlot, 'Color', [ 0.2 0.8 0.2 ], 'LineWidth', 2 );
hold on;
plot( difPlot, 'Color', [ 0.8 0.2 0.2 ], 'LineWidth', 3 );
hold on;

% grid and labels
grid on
yMin = min( [ min( idlPlot ) min( strPlot ) min( difPlot ) ] );
yMax = max( [ max( idlPlot ) max( strPlot ) max( difPlot ) ] );
axis( [ 0 halfWinSize yMin yMax ]);
set( gca, 'XTick', [ 0 : ( halfWinSize / ( sr / 4000 ) ) : halfWinSize ] );
set( gca, 'XTickLabel', [ 0 : 2000 : ( sr / 2 ) ] );
xlabel( 'Frequency' );
ylabel( 'Sones' );

% legend
xPos = ( halfWinSize + halfWinSize * -xSpc );
yPos = yMax * ySpc;
leg = legend( 'Ideal', 'Stretch', 'Error' );
set( leg, 'Location', 'NorthEast' );
maxStr = sprintf( ' Max: %2.5f', difMax );
meanStr = sprintf( ' Avg: %2.5f', difMean );
legStr = sprintf( '  Sones Error\n%s\n%s', maxStr, meanStr );
text( xPos, yPos, legStr, 'BackgroundColor', 'w', 'EdgeColor', 'k' );

% tighten up figure borders
tightfig();

% Save Data to Files
%--------------------------------------------------------------------------

% get file name
[ a, fileName, b ] = fileparts( strFile );

% write plot to file
hgexport( fig, [ fileName, '.avg.eps' ] );

% write error data to files
csvFile = sprintf( '%s.avg.err.csv', fileName );
csvwrite( csvFile, difPlot );

% EOF
